package com.guonl.controller;

import com.guonl.exception.BusinessException;
import com.guonl.feign.OrderFeign;
import com.guonl.model.ResponseResult;
import io.vavr.control.Try;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private OrderFeign orderFeign;

    @GetMapping("/getUser")
    public ResponseResult getUser() {
        Map map = getUserMap();
        return ResponseResult.ok(map);
    }

    private Map getUserMap() {
        Map map = new HashMap();
        map.put("id", 1);
        map.put("name", "张三");
        map.put("email", "123@qq.com");
        return map;
    }

    @GetMapping("/feign/getUserOrder")
    public ResponseResult getUserOrder(String orderId) {
        Map map = getUserMap();
        Map orderMap = getOrderMap(orderId);
        map.put("order", orderMap);
        return ResponseResult.ok(map);
    }

    private Map getOrderMap(String orderId) {

        Map map = (Map) Try.of(() -> orderFeign.getOrder(orderId))
                .onSuccess(v -> log.info(v.getMsg()))
                .map(nullResp -> nullResp.getData())
                .getOrElseThrow(e -> {
                    log.error(e.getMessage(), e);
                    throw new IllegalStateException(e.getMessage(), e);
                });

        return map;

//        ResponseResult responseResult = orderFeign.getOrder(orderId);
//        if (responseResult.getCode() != 0) {
//            log.error("接口调用失败:{}", responseResult.getMsg());
//            throw new BusinessException(responseResult.getMsg());
//        }
//        return (Map) responseResult.getData();
    }

}
